//
//  LocationApi.swift
//  amap
//
//  Created by James Karl on 2020/5/13.
//

import Foundation
import MAMapKit
import AMapLocationKit

class LocationApi : FlutterApi {
    var cachedLocation: MapLocation?
    
    func handle(mapView: MAMapView, methodId: String,  data: Any?) -> ReplyToFlutter? {
        var result: ReplyToFlutter? = nil
        switch methodId {
        case "getMyLocation":  result = getMyLocation(mapView: mapView,data: data)
        default:
            result = nil
        }
        return result
    }
    
    private func getMyLocation(mapView: MAMapView, data: Any?) -> ReplyToFlutter {
        if let currentLocation = mapView.userLocation {
            LocationService.shared.locationManager.requestLocation(withReGeocode: true) { (location , gecode , error) in
                self.cachedLocation = MapLocation(location: location, regeocode: gecode, error: error)
                return
            }
            
            if cachedLocation != nil {
                return ReplyToFlutter.success(data: cachedLocation?.toMap())
            }
            
            let mapLocation = MapLocation(location: currentLocation)
            if mapLocation.latitude != nil && mapLocation.longitude != nil {
                return ReplyToFlutter.success(data: mapLocation.toMap())
            }
        }
        return ReplyToFlutter.failed(message: "获取当前位置信息失败")
    }
}
